package com.xfcycle.zebrabikegp.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;

import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.constant.BluetoothDeviceConstant;
import com.xfcycle.zebrabikegp.constant.TimingConstant;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.listener.OnTimeOutListener;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;
import com.xfcycle.zebrabikegp.util.HandleDataBySharePreferencesUtil;
import com.xfcycle.zebrabikegp.util.TimingThreadUtil;

/**
 * 传感器灵敏度设值，主要包括行车角度和大灯
 */
public class BsSensorCalibrationActivity extends RootActivity {

    private static final String TAG = "SensorCalibration";

    private ImageView iv_sensor_calibration_back;

    //    private TextView tv_sensor_calibration_angle;
    //    private SeekBar sb_sensor_calibration_angle;

    //    private TextView tv_sensor_calibration_head_light;
    private SeekBar sb_sensor_calibration_head_light;

    private ProgressBar pb_sensor_calibration_environment;
//    private TextView tv_sensor_calibration_environment;

    private Switch switch_auto_headLight;

    private HandleDataByBLEUtil handleDataByBLEUtil;
    private HandleDataBySharePreferencesUtil handleDataBySharePreferencesUtil;

    private Integer angleAmount = 50;
    private Integer headLightAmount = 50;

    //记录按下之前自动大灯的状态
    private boolean isAutomaticHeadLightChecked;
    private SensorCalibrationHandleDataFromBleReceiver sensorCalibrationHandleDataFromBleReceiver;

    private TimingThreadUtil timingThreadUtil;
    private boolean isTimingStart = false;
    private ProgressDialog progressDialog;
    private boolean isManualCheck = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bs_sensor_calibration);

        initView();
        initViewListener();
        setViewContent();
    }

    @Override
    protected void onResume() {
        super.onResume();

        //注册广播
        sensorCalibrationHandleDataFromBleReceiver = new SensorCalibrationHandleDataFromBleReceiver();
        registBroadcastReceiverAtActivity(sensorCalibrationHandleDataFromBleReceiver, BluetoothDeviceConstant.GET_DATA_FROM_BLUETOOTH_BROADCAST_RECEIVER_ACTION);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //回收广播接收者
        unregisterReceiver(sensorCalibrationHandleDataFromBleReceiver);

        //关闭查询电量定时器
        timingThreadUtil.closeThread(TimingConstant.ENVIRONMENT_LIGHT_THREAD_NAME);
        isTimingStart = false;
    }

    /***********************************************************************************************/
    /**                                 初始化控件对象 监听 控件内容方法                             **/
    /***********************************************************************************************/

    private void initView() {
        iv_sensor_calibration_back = (ImageView) findViewById(R.id.iv_sensor_calibration_back);

//        sb_sensor_calibration_angle = (SeekBar) findViewById(R.id.sb_sensor_calibration_angle);
//        tv_sensor_calibration_angle = (TextView) findViewById(R.id.tv_sensor_calibration_angle);

        sb_sensor_calibration_head_light = (SeekBar) findViewById(R.id.sb_sensor_calibration_head_light);
//        tv_sensor_calibration_head_light = (TextView) findViewById(R.id.tv_sensor_calibration_head_light);

        pb_sensor_calibration_environment = (ProgressBar) findViewById(R.id.sb_sensor_calibration_environment);
//        tv_sensor_calibration_environment = (TextView) findViewById(R.id.tv_sensor_calibration_environment);

        switch_auto_headLight = (Switch) findViewById(R.id.switch_auto_headLight);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, -1);
        handleDataBySharePreferencesUtil = HandleDataBySharePreferencesUtil.getInstance(this);

        timingThreadUtil = TimingThreadUtil.getInstance(TimingConstant.ENVIRONMENT_LIGHT_THREAD_NAME, new OnTimeOutListener() {
            @Override
            public void timeOut() {
                handleDataByBLEUtil.sendDataToDevice("s|1,2");
            }
        });

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("wait...");
        progressDialog.setCancelable(true);
    }

    private void initViewListener() {
        //回退事件监听
        iv_sensor_calibration_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        //监听是否手动改变
        switch_auto_headLight.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        isManualCheck = true;
                        break;
                }
                return false;
            }
        });

        //用户调整大灯是否自动开启
        switch_auto_headLight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isAutomaticHeadLightChecked = isChecked;
                if (!isManualCheck) {
                    return;
                }

                Log.w(TAG, "onCheckedChanged: -------------------- 当前自动大灯的选择状态："+isChecked);

                if (isChecked) {
                    handleDataByBLEUtil.sendDataToDevice("s|1,1," + sb_sensor_calibration_head_light.getProgress());
                    sb_sensor_calibration_head_light.setEnabled(true);
                    return;
                }
                handleDataByBLEUtil.sendDataToDevice("s|1,0");
                sb_sensor_calibration_head_light.setEnabled(false);
            }
        });

        //设置车前大灯的灵敏度 依据周围环境的光暗
        sb_sensor_calibration_head_light.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                String result = seekBar.getProgress() + "";

                if (null == result) {
                    Log.e(TAG, "onStopTrackingTouch: seekBar 车大灯 获取的亮度值为空");
                    return;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                headLightAmount = seekBar.getProgress();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                String result = 100 - seekBar.getProgress() + "";

                if (null == result) {
                    Log.e(TAG, "onStopTrackingTouch: seekBar 车大灯 获取的亮度值为空");
                    return;
                }

                handleDataByBLEUtil.sendDataToDevice("s|1,1," + result);

                if (BlueToothAssist.isUnlock) {
                    progressDialog.show();
                }
            }
        });
    }

    private void setViewContent() {
        handleDataByBLEUtil.sendDataToDevice("s|1,2");
    }

    /***********************************************************************************************/
    /**                                 自定义广播接收者类                                          **/
    /***********************************************************************************************/

    /**
     * 广播接收者类，负责接收从蓝牙发出的数据并对其进行处理
     */
    class SensorCalibrationHandleDataFromBleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("result");

            Log.w(TAG, "onReceive: ------------- " + result);

            isManualCheck = false;
            //修改大灯状态成功
            if (result.contains("^s|1,0")) {
                Toast.makeText(context.getApplicationContext(), ToastConstant.MODIFY_HEADLIGHT_STATE_SUCCESS, Toast.LENGTH_SHORT).show();
                return;
            }

            if (result.contains("^s|1,1")) {
                switch_auto_headLight.setChecked(true);
                SystemClock.sleep(2000);
                if (null != progressDialog && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                Toast.makeText(context.getApplicationContext(), ToastConstant.MODIFY_HEADLIGHT_STATE_SUCCESS, Toast.LENGTH_SHORT).show();
                return;
            }

            //读取环境亮度
            if (result.contains("^s|1,2")) {
                Integer brightness = Integer.parseInt(result.replace("^s|1,2,", "").replace("$", ""));
                pb_sensor_calibration_environment.setProgress(100 - brightness);
                if (!isTimingStart) {
                    handleDataByBLEUtil.sendDataToDevice("s|1,3");
                }
                return;
            }

            //读取之前灵敏度
            if (result.contains("^s|1,3")) {
                Integer brightness = Integer.parseInt(result.replace("^s|1,3,", "").replace("$", ""));
                sb_sensor_calibration_head_light.setProgress(100 - brightness);
                handleDataByBLEUtil.sendDataToDevice("s|1,4");
                return;
            }

            //读取自动大灯是否开启
            if (result.contains("^s|1,4")) {
                String lightState = result.replace("^s|1,4,", "").replace("$", "");

                Log.w(TAG, "onReceive: -------------- " + lightState);
                if ("0".equals(lightState)) {
                    Log.w(TAG, "onReceive: -------------- false");
                    switch_auto_headLight.setChecked(false);
                    sb_sensor_calibration_head_light.setEnabled(false);
                }

                if ("1".equals(lightState)) {
                    Log.w(TAG, "onReceive: -------------- true");
                    switch_auto_headLight.setChecked(true);
                    sb_sensor_calibration_head_light.setEnabled(true);
                }

                //开启查询电量定时器
                if (BlueToothAssist.isUnlock) {
                    Log.w(TAG, "onReceive: ------------------ 定时查询 -- 环境亮度");
                    timingThreadUtil.openThread(TimingConstant.ENVIRONMENT_LIGHT_THREAD_NAME, TimingConstant.ENVIRONMENT_LIGHT_TIME);
                    isTimingStart = true;
                }

                if (null != progressDialog && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }

                return;
            }

            //修改助力 大灯灵敏度至初始状态
            switch_auto_headLight.setChecked(!isAutomaticHeadLightChecked);
        }
    }

}
